﻿using MesGLApp.BLL.Mes;
using MesGLApp.DAL.MesDB;
using MesGLApp.DAL.MesDTO;
using MesGLApp.DAL.RoleDB;
using MesGLApp.DAL.RoleDTO;
using Smobiler.Core;
using Smobiler.Core.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MesGLApp.View.Scan
{
    partial class ProductWarehousingFrm : Smobiler.Core.Controls.MobileForm
    {
        #region "内部变量"
        private ProdProcScanControler _scan_ctrl = new ProdProcScanControler();
        private TargetProdProcessDTO _curr_prod = null;
        private SiteInfo _curr_site = null;
        private StatusInfo _curr_status = null;

        private List<SiteInfo> _site_list = new List<SiteInfo>();
        private List<StatusInfo> _status_list = new List<StatusInfo>();
        #endregion

        public ProductWarehousingFrm() : base()
        {
            //This call is required by the SmobilerForm.
            InitializeComponent();
        }

        #region "控件事件"
        /// <summary>
        /// 关闭页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Press(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 读入界面时，读取包装结束站的信息和对应的工单状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProductWarehousingFrm_Load(object sender, EventArgs e)
        {
            this.LoadBaseData();
            if (this._curr_site != null)
            {
                this.lblSiteName.Text = this._curr_site.SiteName;
            }

            if (this._curr_status != null)
            {
                this.lblStatusName.Text = this._curr_status.StatusValue;
            }

            this.btnSave.Enabled = false;
        }

        /// <summary>
        /// 扫码录入工单号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnScan_BarcodeScanned(object sender, BarcodeResultArgs e)
        {
            string prodNo = e.Value.ToString();
            this.txtProdNumber.Text = prodNo;

            this._curr_prod = this._scan_ctrl.SearchTargetForScan(prodNo);
            if (this._curr_prod != null && this._curr_prod.ID > 0)
            {
                this.lblProdQty.Text = Math.Round(this._curr_prod.ProdQty ?? 0, 2).ToString();

                decimal clearQty = 0;
                List<ProdProcScan> scanList = this._scan_ctrl.SearchScanForCondition(prodNo, this._curr_site.ID);
                if (scanList != null && scanList.Count > 0)
                {
                    clearQty = scanList.Sum(s => s.ScanQty);
                }
                this.lblClearQty.Text = Math.Round(clearQty, 2).ToString();

                this.txtScanQty.Text = Math.Round((this._curr_prod.ProdQty ?? 0) - clearQty, 2).ToString();

                this.btnSave.Enabled = true;
            }
            else
            {
                Toast("无此工单号！", ToastLength.LONG);
            }
        }

        /// <summary>
        /// 手输工单号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtProdNumber_SubmitEditing(object sender, EventArgs e)
        {
            //取得工单号
            string prodNo = this.txtProdNumber.Text;
            //根据工单号查询工单信息
            this._curr_prod = this._scan_ctrl.SearchTargetForScan(prodNo);
            if (this._curr_prod != null && this._curr_prod.ID > 0)
            {
                this.lblProdQty.Text = Math.Round(this._curr_prod.ProdQty ?? 0, 2).ToString();

                //再通过工单号找到工单的投产数量、已扫码的数量
                decimal clearQty = 0;
                List<ProdProcScan> scanList = this._scan_ctrl.SearchScanForCondition(prodNo, this._curr_site.ID);
                if (scanList != null && scanList.Count > 0)
                {
                    clearQty = scanList.Sum(s => s.ScanQty);
                }
                this.lblClearQty.Text = Math.Round(clearQty, 2).ToString();

                //本次可扫码数量 = 投产数量 - 已扫数量
                this.txtScanQty.Text = Math.Round((this._curr_prod.ProdQty ?? 0) - clearQty, 2).ToString();

                this.btnSave.Enabled = true;
            }
            else
            {
                Toast("无此工单号！", ToastLength.LONG);
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Press(object sender, EventArgs e)
        {
            decimal inStockQty = 0;
            if (decimal.TryParse(this.txtScanQty.Text.Trim(), out inStockQty) == false || decimal.Parse(this.txtScanQty.Text.Trim()) > 0)
            {
                MessageBox.Show("本次入库必需是大于0的数值型！");
            }
            else
            {
                inStockQty = decimal.Parse(this.txtScanQty.Text.Trim());
                string errStr = this.CheckData(this._curr_prod, this._curr_site, this._curr_status, inStockQty);
                if (errStr != null && errStr.Trim().Length > 0)
                {
                    MessageBox.Show(errStr);
                }
                else
                {
                    BaseUserModel tmpUser = new BaseUserModel();
                    Tools.EntityTools.CopyEntity<BaseUserDTO, BaseUserModel>(LoginFrm.LoginUser, ref tmpUser);
                    try
                    {
                        int count = this._scan_ctrl.SaveProdProcessScan(this._curr_prod, tmpUser, this._curr_site, this._curr_status, inStockQty);
                        Toast("扫码成功！", ToastLength.LONG);
                        this.txtProdNumber.Text = "";
                        this.lblProdQty1.Text = "";
                        this.lblClearQty.Text = "";
                        this.txtScanQty.Text = "";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("扫码失败！" + "/r/n" + ex.Message);
                    }
                }
            }
        }
        #endregion

        #region "内部方法"
        /// <summary>
        /// 读取基础数据
        /// </summary>
        private void LoadBaseData()
        {
            this._site_list = this._scan_ctrl.SearchAllSiteInfo();
            this._status_list = this._scan_ctrl.SearchAllStatus();

            if (this._site_list != null && this._site_list.Count > 0)
            {
                var siteQuery = this._site_list.Where(s => s.SiteName == "包装结束");
                if (siteQuery != null && siteQuery.Count() > 0)
                {
                    this._curr_site = siteQuery.First<SiteInfo>();
                    if (this._status_list != null && this._status_list.Count > 0)
                    {
                        var statusQuery = this._status_list.AsQueryable<StatusInfo>();
                        if (this._curr_site != null && (this._curr_site.DefStatus ?? 0) > 0)
                        {
                            statusQuery = statusQuery.Where(s => s.ID == (this._curr_site.DefStatus ?? 0));
                        }
                        else
                        {
                            statusQuery = statusQuery.Where(s => s.StatusValue == "已完成");
                        }

                        if (statusQuery != null && statusQuery.Count() > 0)
                        {
                            this._curr_status = statusQuery.First<StatusInfo>();
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 检查数据是否正常
        /// </summary>
        /// <param name="prod">工单</param>
        /// <param name="site">站点</param>
        /// <param name="status">状态</param>
        /// <param name="scanQty">本次入库数量</param>
        /// <returns></returns>
        private string CheckData(TargetProdProcessDTO prod,SiteInfo site,StatusInfo status,decimal scanQty)
        {
            string errStr = "";
            if (site == null || site.ID <= 0)
            {
                errStr = "当前站点为空，中止扫码！";
            }
            else if (status == null || status.ID <= 0)
            {
                errStr = "当前工单状态为空，中止扫码！";
            }
            else if (prod == null || prod.ID <= 0)
            {
                errStr = "当前工单为空，中止扫码！";
            }
            else if (prod.SiteGroup == null || prod.SiteGroup.SiteInfoList == null || prod.SiteGroup.SiteInfoList.Count <= 0)
            {
                errStr = "当前工单没分配站点组，中止扫码！";
            }
            else if (prod.SiteGroup.SiteInfoList.Where(s => s.SiteID == site.ID).Count() <= 0)
            {
                errStr = "当前工单不需要经过" + site.SiteName + "站";
            }
            else
            {
                SiteInfo lastSite = null;
                int tmpIndex = 0;
                decimal lastQty = 0;
                decimal clearQty = 0;

                List<ProdProcScan> scanList = this._scan_ctrl.SearchScanForProdNumber(prod.ProdNumber);
                prod.SiteGroup.SiteInfoList.OrderBy(s => s.Sort).ToList().ForEach(s => {
                    if (s.SiteID == site.ID)
                    {
                        tmpIndex = prod.SiteGroup.SiteInfoList.OrderBy(tmpSite => tmpSite.Sort).ToList().IndexOf(s);
                        if (tmpIndex > 0)
                        {
                            lastSite = prod.SiteGroup.SiteInfoList.OrderBy(tmpSite => tmpSite.Sort).ToList()[tmpIndex - 1].SiteInfo;
                        }
                    }
                });

                if (tmpIndex > 0 && lastSite == null)
                {
                    errStr = "无法找到上一站点信息，中止扫码！";
                }
                else
                {
                    if (tmpIndex == 0)
                    {
                        lastQty = prod.ProdQty ?? 0;
                    }
                    else
                    {
                        lastQty = scanList.Where(s => s.SiteInfoID == lastSite.ID).Sum(s => s.ScanQty);
                    }

                    clearQty = scanList.Where(s => s.SiteInfoID == site.ID).Sum(s => s.ScanQty);

                    if (lastQty < clearQty + scanQty)
                    {
                        errStr = "已入库数量 + 本次入库数量 不能大于 总数量";
                    }
                }
            }
            return errStr;
        }

        #endregion

        
    }
}